package com.qiguliuxing.dts.service.base;

import com.qiguliuxing.dts.common.type.OrderStatusEnum;
import com.qiguliuxing.dts.db.dao.DtsOrderGoodsMapper;
import com.qiguliuxing.dts.db.dao.DtsOrderMapper;
import com.qiguliuxing.dts.db.dao.DtsRefundTraceMapper;
import com.qiguliuxing.dts.db.dao.ex.OrderMapper;
import com.qiguliuxing.dts.db.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class DtsRefundService {
    @Resource
    private DtsOrderMapper dtsOrderMapper;
	@Resource
	private OrderMapper orderMapper;
    @Resource
    private DtsOrderGoodsMapper orderGoodsMapper;
    @Resource
    private DtsRefundTraceMapper refundTraceMapper;

    /**
     * 然后 生成申请的退货跟踪记录信息
     * 1.存储退货跟踪记录
     * 2.订单商品表记录必须绑定退货跟踪编号
     * 3.验证是否改订单中所有的商品都有退货申请（已绑定退货编号）,如果都已申请退货，调整订单状态为退货中
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public Integer refundApply(DtsOrder order,Integer userId, Integer orderId,Short orderStatus, List<Integer> productIds, BigDecimal refundApplyAmount, String refundReason,Byte refundType,Integer num) {
	    //如果申请的退款金额不存在，则需根据订单和商品id获取所有需退货商品的金额
        if (refundApplyAmount == null) {
            DtsOrderGoodsExample example = new DtsOrderGoodsExample();
            example.or().andOrderIdEqualTo(orderId).andProductIdIn(productIds).andDeletedEqualTo(false);
            List<DtsOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(example);
            BigDecimal tempApplyAmount = new BigDecimal(0);
            for (DtsOrderGoods orderGoods : orderGoodsList) {
                tempApplyAmount = tempApplyAmount.add(orderGoods.getPrice().multiply(new BigDecimal(orderGoods.getNumber())));
            }
            refundApplyAmount = tempApplyAmount;
        }

        //存储退款跟踪记录
        DtsRefundTrace refundTrace = new DtsRefundTrace();
        refundTrace.setRefundSn(generateOrderSn(userId));//生成一个退货序号
        refundTrace.setHasPicture(false);//暂设置无图片
        refundTrace.setOrderStatus(orderStatus);
        refundTrace.setOrderId(orderId);
        refundTrace.setOrderSn(order.getOrderSn());
        refundTrace.setAddTime(LocalDateTime.now());
        refundTrace.setStatus((byte) 0);//默认为待审批状态
        refundTrace.setRefundReason(refundReason);
        refundTrace.setRefundApplyAmount(refundApplyAmount);
        refundTrace.setUserId(userId);
        refundTrace.setUpdateTime(LocalDateTime.now());
        refundTrace.setRefundType(refundType);
        refundTrace.setNum(num);
        refundTraceMapper.insertSelective(refundTrace);
        Integer refundId = refundTrace.getId();

        //存储订单商品绑定退款id
        for (Integer productId : productIds) {
            DtsOrderGoods record = new DtsOrderGoods();
            record.setRefundId(refundId);
            DtsOrderGoodsExample orderGoodsExample = new DtsOrderGoodsExample();
            orderGoodsExample.or().andOrderIdEqualTo(orderId).andProductIdEqualTo(productId);
            orderGoodsMapper.updateByExampleSelective(record,orderGoodsExample);
        }

        //验证是否所有商品都申请退款,如果整个订单的商品都已经申请退款，则订单处于退款中...
        DtsOrderGoodsExample example = new DtsOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andRefundIdIsNull();
        long count = orderGoodsMapper.countByExample(example);
        if (count < 1){ //已经全部退货
            order.setOrderStatus(OrderStatusEnum.REFUND.status);
            LocalDateTime preUpdateTime = order.getUpdateTime();
            order.setUpdateTime(LocalDateTime.now());
            orderMapper.updateWithOptimisticLocker(preUpdateTime,order);
        }
        return refundId;
	}

    public String generateOrderSn(Integer userId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String now = df.format(LocalDateTime.now());
        String orderSn = now + getRandomNum(8);
        return orderSn;
    }

    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public DtsRefundTrace findRefundTraceById(Integer refundId) {
        return refundTraceMapper.selectByPrimaryKey(refundId);
    }

    public List<DtsOrderGoods> queryOrderGoodsByRefundId(Integer refundId) {
        DtsOrderGoodsExample example = new DtsOrderGoodsExample();
        example.or().andRefundIdEqualTo(refundId);
        return orderGoodsMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public boolean refundUndo(Integer refundId) {
        refundTraceMapper.logicalDeleteByPrimaryKey(refundId);//删除退货申请记录

        List<DtsOrderGoods> refundOrderGoods = this.queryOrderGoodsByRefundId(refundId);
        for (DtsOrderGoods orderGoods : refundOrderGoods) {
            orderGoods.setRefundId(null);//删除管理的退款id
            orderGoodsMapper.updateByPrimaryKey(orderGoods);
        }

        //如果对应商品的购买订单状态为退款中,则需要恢复原来订单的状态
        DtsRefundTrace refundTrace = refundTraceMapper.selectByPrimaryKey(refundId);
        DtsOrder order = dtsOrderMapper.selectByPrimaryKey(refundTrace.getOrderId());
        if (order.getOrderStatus().intValue() == OrderStatusEnum.REFUND.status.intValue()) { //如果订单属于退款
            if (order.getShipTime() == null) {//未发货
                order.setOrderStatus(OrderStatusEnum.PAY.status);
            } else {
                order.setOrderStatus(OrderStatusEnum.SHIP.status);
            }
            LocalDateTime preUpdateTime = order.getUpdateTime();
            order.setUpdateTime(LocalDateTime.now());
            orderMapper.updateWithOptimisticLocker(preUpdateTime,order);
        }
        return true;
    }

    public void updateFreightMsg(Integer refundId, String freightMsg) {
        DtsRefundTrace refundTrace = new DtsRefundTrace();
        refundTrace.setFreightMsg(freightMsg);
        refundTrace.setId(refundId);
        refundTraceMapper.updateByPrimaryKeySelective(refundTrace);
    }

    public void deleteRefundById(Integer id) {
        refundTraceMapper.deleteByPrimaryKey(id);
    }
    /**
     * 根据订单ID获取所有退货子订单
     * @param orderId
     * @return
     */
    public List<DtsRefundTrace> findRefundTraceByOrderId(Integer orderId) {
        DtsRefundTraceExample example = new DtsRefundTraceExample();
        example.or().andDeletedEqualTo(false).andOrderIdEqualTo(orderId);
        return refundTraceMapper.selectByExample(example);
    }

    /**
     * 根据订单ID获取是否存在退货子订单
     * @param orderId
     * @param finishRefundStatus 3 退款完成状态
     * @return
     */
    public Long unFinishCntRefundByOrderId(Integer orderId,Byte finishRefundStatus) {
        DtsRefundTraceExample example = new DtsRefundTraceExample();
        example.or().andDeletedEqualTo(false).andOrderIdEqualTo(orderId).andStatusNotEqualTo(finishRefundStatus);
        return refundTraceMapper.countByExample(example);
    }

    /**
     * 审批退款订单
     * @param refundId
     * @param approveStatus
     * @param approveMsg
     * @param approveMsg
     */
    public void approveRefund(Integer refundId, Byte approveStatus, String approveMsg,String refundAmount) {
        DtsRefundTrace refundTrace = new DtsRefundTrace();
        refundTrace.setId(refundId);
        refundTrace.setStatus(approveStatus);
        refundTrace.setApproveMsg(approveMsg);
        refundTrace.setRefundAmount(new BigDecimal(refundAmount));
        refundTrace.setApproveTime(LocalDateTime.now());
        refundTraceMapper.updateByPrimaryKeySelective(refundTrace);
    }
}
